<template>
  <div class="voice-call-overlay" v-if="visible">
    <!-- 背景模糊层 -->
    <div class="backdrop"></div>
    
    <!-- 主要内容 -->
    <div class="content">
      <!-- 顶部状态 -->
      <div class="status-bar">
        <div class="connection-status">
          <div class="status-dot"></div>
          <span>通话中</span>
        </div>
        <div class="call-duration">{{ durationFormatted }}</div>
      </div>

      <!-- 中间 Agent 头像区域 -->
      <div class="avatar-section" @click="$emit('minimize')">
        <div class="wave-container" :style="{ '--agent-energy': agentEnergy }">
          <!-- 真实声纹可视化 -->
          <div class="wave w1"></div>
          <div class="wave w2"></div>
          <div class="wave w3"></div>
        </div>
        <div class="avatar-container">
          <div class="avatar-wrapper">
            <el-icon class="avatar-icon" :size="64"><Service /></el-icon>
          </div>
          <div class="click-hint">点击查看文字记录</div>
        </div>
        <h2 class="agent-name">{{ agentName }}</h2>
      </div>

      <!-- 底部用户区域 & 控制栏 -->
      <div class="bottom-section">
        <!-- 对话显示区域 -->
        <div class="conversation-display">
          <!-- 用户识别结果 -->
          <div v-if="displayUserText" class="message-item user-message">
            <div class="message-label">你说：</div>
            <div class="message-text">{{ displayUserText }}</div>
          </div>
          
          <!-- AI回复 -->
          <div v-if="displayAgentText" class="message-item agent-message">
            <div class="message-label">AI：</div>
            <div class="message-text">{{ displayAgentText }}</div>
          </div>
        </div>

        <!-- 底部波形 (用户/双方) -->
        <div class="waveform-visualizer">
          <div v-for="(height, i) in userBars" :key="i" class="bar" :class="{ active: isUserSpeaking }" :style="{ height: `${height}px` }"></div>
        </div>

        <!-- 控制按钮 -->
        <div class="controls">
          <div class="control-item">
            <el-button circle size="large" :class="{ 'is-active': isMuted }" @click="toggleMute">
              <el-icon><Microphone v-if="!isMuted" /><Mute v-else /></el-icon>
            </el-button>
            <span>{{ isMuted ? '已静音' : '麦克风' }}</span>
          </div>

          <div class="control-item hangup">
            <el-button circle size="large" type="danger" class="hangup-btn" @click="$emit('close')">
              <el-icon><PhoneFilled /></el-icon>
            </el-button>
            <span>挂断</span>
          </div>

          <div class="control-item">
            <el-button circle size="large" @click="$emit('minimize')">
              <el-icon><ChatDotRound /></el-icon>
            </el-button>
            <span>文字</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, watch } from 'vue'
import { Service, PhoneFilled, Microphone, Mute, ChatDotRound } from '@element-plus/icons-vue'

const props = defineProps({
  visible: Boolean,
  agentName: {
    type: String,
    default: 'AI Assistant'
  },
  isAgentSpeaking: {
    type: Boolean,
    default: false
  },
  transcriptionText: {
    type: String,
    default: ''
  },
  isUserSpeaking: {
    type: Boolean,
    default: false
  },
  userAnalyser: {
    type: Object,
    default: null
  },
  agentAnalyser: {
    type: Object,
    default: null
  },
  agentResponseText: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['close', 'minimize', 'toggle-mute', 'send-transcription'])

// 通话时长
const duration = ref(0)
let timer = null

// 显示的文本
const displayUserText = ref('')
const displayAgentText = ref('')

const durationFormatted = computed(() => {
  const minutes = Math.floor(duration.value / 60)
  const seconds = duration.value % 60
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
})

// 静音状态
const isMuted = ref(false)
const toggleMute = () => {
  isMuted.value = !isMuted.value
  emit('toggle-mute', isMuted.value)
}

// 实时波形数据
const userBars = ref(new Array(30).fill(10)) // 增加条数让视觉更丰富
const agentEnergy = ref(0)
let animationFrameId = null

// 更新波形数据
const updateVisualizer = () => {
  // 1. 更新用户波形 (User Analyser)
  if (props.userAnalyser) {
    const dataArray = new Uint8Array(props.userAnalyser.frequencyBinCount)
    props.userAnalyser.getByteFrequencyData(dataArray)
    
    // 取一部分频率范围（人声通常在低频到中频）
    // 简单的线性采样
    const step = Math.floor(dataArray.length / 100) // 采样跨度
    const bars = []
    for (let i = 0; i < 30; i++) {
      // 获取对应频率的能量值
      const value = dataArray[i * step] || 0
      // 映射高度: 最小4px，最大50px
      const height = 4 + (value / 255) * 46
      bars.push(height)
    }
    userBars.value = bars
  } else {
    // 如果没有真实数据但正在说话，显示随机动画 (或者保持静止)
    if (props.isUserSpeaking) {
       userBars.value = userBars.value.map(() => 10 + Math.random() * 30)
    } else {
       userBars.value = new Array(30).fill(4)
    }
  }

  // 2. 更新 Agent 波形 (Agent Analyser)
  if (props.agentAnalyser) {
    const dataArray = new Uint8Array(props.agentAnalyser.frequencyBinCount)
    props.agentAnalyser.getByteFrequencyData(dataArray)
    
    // 计算平均能量
    let sum = 0
    for (let i = 0; i < dataArray.length; i++) {
      sum += dataArray[i]
    }
    const average = sum / dataArray.length
    // 平滑处理
    agentEnergy.value = agentEnergy.value * 0.8 + (average / 255) * 0.2
  } else {
    // 如果没有真实数据但正在说话，模拟能量
    if (props.isAgentSpeaking) {
      agentEnergy.value = 0.5 + Math.random() * 0.3
    } else {
      agentEnergy.value = Math.max(0, agentEnergy.value - 0.05)
    }
  }

  animationFrameId = requestAnimationFrame(updateVisualizer)
}

// 监听 analyser 变化
watch(() => [props.userAnalyser, props.agentAnalyser], () => {
  // 确保动画循环在运行
  if (!animationFrameId) {
    updateVisualizer()
  }
}, { immediate: true })

// 监听识别文本变化，自动发送
watch(() => props.transcriptionText, (newText) => {
  if (newText && newText.trim()) {
    // 更新显示的用户文本
    displayUserText.value = newText
    // 自动发送
    emit('send-transcription', newText.trim())
  }
})

// 监听AI回复文本变化
watch(() => props.agentResponseText, (newText) => {
  if (newText && newText.trim()) {
    displayAgentText.value = newText
  } else {
    // 当AI回复被清空时，也清空显示
    displayAgentText.value = ''
  }
})

onMounted(() => {
  timer = setInterval(() => {
    duration.value++
  }, 1000)
  updateVisualizer()
})

onUnmounted(() => {
  if (timer) clearInterval(timer)
  if (animationFrameId) cancelAnimationFrame(animationFrameId)
})
</script>

<style scoped>
.voice-call-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 2000;
  overflow: hidden;
  color: white;
  display: flex;
  flex-direction: column;
}

.backdrop {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(180deg, #1a1f3c 0%, #0f1222 100%);
  opacity: 0.98;
}

/* 如果有背景图，可以加一个模糊层 */
.backdrop::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: radial-gradient(circle at 50% 30%, rgba(76, 110, 245, 0.15), transparent 70%);
}

.content {
  position: relative;
  z-index: 1;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 2rem;
}

.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 0.9rem;
  color: rgba(255, 255, 255, 0.7);
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-dot {
  width: 8px;
  height: 8px;
  background-color: #4ade80;
  border-radius: 50%;
  box-shadow: 0 0 8px #4ade80;
}

/* Avatar Section */
.avatar-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.avatar-section:hover {
  transform: scale(1.02);
}

.avatar-container {
  position: relative;
  margin-bottom: 1.5rem;
}

.avatar-wrapper {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  position: relative;
  z-index: 2;
}

.avatar-icon {
  font-size: 64px;
  color: white;
}

.click-hint {
  position: absolute;
  bottom: -30px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 12px;
  color: rgba(255, 255, 255, 0.5);
  white-space: nowrap;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-section:hover .click-hint {
  opacity: 1;
}

.agent-name {
  font-size: 1.5rem;
  font-weight: 600;
  color: white;
  text-shadow: 0 2px 4px rgba(0,0,0,0.5);
}

/* Waves Animation */
.wave-container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 120px;
  height: 120px;
  --agent-energy: 0; /* Default value */
}

.wave {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border-radius: 50%;
  width: 100%;
  height: 100%;
  opacity: 0;
  border: 2px solid rgba(102, 126, 234, calc(0.3 + var(--agent-energy) * 0.7));
  box-shadow: 0 0 calc(30px * var(--agent-energy)) rgba(102, 126, 234, 0.4);
  animation: ripple 2s infinite cubic-bezier(0, 0.2, 0.8, 1);
}

.w1 { animation-delay: 0s; }
.w2 { animation-delay: -0.6s; }
.w3 { animation-delay: -1.2s; }

@keyframes ripple {
  0% {
    width: 100%;
    height: 100%;
    opacity: calc(0.8 * var(--agent-energy));
    border-width: 3px;
  }
  100% {
    width: 350%;
    height: 350%;
    opacity: 0;
    border-width: 0px;
  }
}

/* Bottom Section */
.bottom-section {
  display: flex;
  flex-direction: column;
  gap: 2rem;
}

/* 对话显示区域 */
.conversation-display {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 16px;
  max-height: 200px;
  overflow-y: auto;
}

.message-item {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 12px 16px;
  animation: slideUp 0.3s ease-out;
}

.user-message {
  background: rgba(76, 110, 245, 0.2);
  border-left: 3px solid rgba(76, 110, 245, 0.8);
}

.agent-message {
  background: rgba(102, 126, 234, 0.2);
  border-left: 3px solid rgba(102, 126, 234, 0.8);
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message-label {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.6);
  margin-bottom: 4px;
  font-weight: 500;
}

.message-text {
  font-size: 14px;
  color: white;
  line-height: 1.5;
  word-break: break-word;
}

.waveform-visualizer {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 4px;
  height: 60px;
}

.bar {
  width: 6px;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 3px;
  transition: height 0.1s ease;
}

.bar.active {
  background: rgba(76, 110, 245, 0.8);
}

.controls {
  display: flex;
  justify-content: space-evenly;
  align-items: flex-start;
}

.control-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
}

.control-item .el-button {
  width: 60px;
  height: 60px;
  background: rgba(255, 255, 255, 0.1);
  border: none;
  color: white;
  font-size: 24px;
  transition: all 0.3s;
}

.control-item .el-button:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: scale(1.1);
}

.control-item .hangup-btn {
  background-color: #ff4d4f;
  width: 72px;
  height: 72px;
  box-shadow: 0 4px 12px rgba(255, 77, 79, 0.4);
}

.control-item .hangup-btn:hover {
  background-color: #ff7875;
}

.control-item .is-active {
  background-color: white;
  color: #333;
}
</style>
